package com.cskaoyan.service;

import com.cskaoyan.bean.bo.WxglMallManagementControllerBo.ClearHistoryBo;
import com.cskaoyan.bean.common.BasePageInfo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.common.Constant;
import com.cskaoyan.bean.marketBean.*;
import com.cskaoyan.bean.vo.WxglMallManagementControllerVo.*;
import com.cskaoyan.mapper.marketMapper.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author wxgl
 * @date 2022-12-31 11:59
 * @describe
 */
@Transactional
@Service
public class WxglCatalogServiceImpl implements WxglCatalogService{
    @Autowired
    MarketCategoryMapper categoryMapper;
    @Autowired
    MarketKeywordMapper keywordMapper;
    @Autowired
    MarketSearchHistoryMapper historyMapper;
    @Autowired
    MarketTopicMapper topicMapper;
    @Autowired
    MarketGoodsMapper goodsMapper;
    @Autowired
    MarketCollectMapper collectMapper;
    @Autowired
    MarketStorageMapper storageMapper;


    /**
     * @Author xiaowu
     * @Description //TODO 显示指定类目的信息
     * @Date 12:01 2022/12/31
     * @Param [id]
     * @return com.cskaoyan.bean.vo.WxglMallManagementControllerVo.CatalogCurrentVo
     **/
    @Override
    public CatalogCurrentVo catalogCurrent(Integer id) {

        MarketCategory marketCategory = categoryMapper.selectByPrimaryKey(id);

        List<MarketCategory> marketCategoryList = categoryMapper.selectCatalogsByPid(id);

        CatalogCurrentVo catalogCurrentVo = new CatalogCurrentVo();
        catalogCurrentVo.setCurrentCategory(marketCategory);
        catalogCurrentVo.setCurrentSubCategory(marketCategoryList);

        return catalogCurrentVo;
    }

    @Override
    public CatalogIndexVo catalogIndex() {
        MarketCategory marketCategory = categoryMapper.selectByPrimaryKey(Constant.DEFAULT_FIRST_CATALOG_LV1_ID);
        List<MarketCategory> marketCategories1 = categoryMapper.selectCatalogsByLevel(Constant.FIRST_LEVLE);
        List<MarketCategory> marketCategories2 = categoryMapper.selectCatalogsByPid(marketCategory.getId());

        CatalogIndexVo catalogIndexVo = new CatalogIndexVo();
        catalogIndexVo.setCurrentCategory(marketCategory);
        catalogIndexVo.setCategoryList(marketCategories1);
        catalogIndexVo.setCurrentSubCategory(marketCategories2);
        return catalogIndexVo;
    }

    @Override
    public SearchIndexVo searchIndex(Integer userId) {
        MarketKeyword defaultKeyword = keywordMapper.selectByPrimaryKey(Constant.DEFAULT_KEYWORD_ID);
        List<MarketKeyword> hotKeywords = keywordMapper.selectKeywordIsHost();

        List<MarketSearchHistory> marketSearchHistories = keywordMapper.selectAllSearchHistory(userId);

        SearchIndexVo searchIndexVo = new SearchIndexVo();
        searchIndexVo.setDefaultKeyword(defaultKeyword);
        searchIndexVo.setHotKeywordList(hotKeywords);
        searchIndexVo.setHistoryKeywordList(marketSearchHistories);

        return searchIndexVo;
    }

    @Override
    public List<String> searchHelper(String keyword) {

        keyword = "%" + keyword +"%";

        List<String> keywords = keywordMapper.searchHelper(keyword);

        return keywords;
    }

    @Override
    public void searchClearhistory(ClearHistoryBo clearHistoryBo) {
//        List<String> historySearch = clearHistoryBo.getHistorySearch();
        historyMapper.searchClearhistory();
    }

    @Override
    public TopicListVo topicList(Integer page, Integer limit) {

        PageHelper.startPage(page,limit);
        //新建一个相关的example类的对象
        MarketTopicExample example = new MarketTopicExample();
        //设置去重
        example.setDistinct(true);
        //使用example对象创建criteria对象
        MarketTopicExample.Criteria criteria = example.createCriteria();

        List<ListDtoVo> listDtoVos = topicMapper.selectParameterByExample(example);
        TopicListVo topicListVo = new TopicListVo();
        int total = topicMapper.selectCountFromTopic();
        topicListVo.setTotal(total);
        int pages = 0;
        if (total%limit == 0){
            pages = total/limit;
        }else {
            pages = total/limit + 1;
        }
        topicListVo.setPages(pages);
        topicListVo.setPage(page);
        topicListVo.setLimit(limit);
        topicListVo.setList(listDtoVos);

        return topicListVo;
    }

    @Override
    public TopicDetailVo topicDetail(Integer id) {
        MarketTopic marketTopic = topicMapper.selectByPrimaryKey(id);

        TopicDetailVo topicDetailVo = new TopicDetailVo();
        topicDetailVo.setTopic(marketTopic);

        Integer[] goods = marketTopic.getGoods();

        List<GoodsDtoVo> goodsDtoVo = goodsMapper.selectInfoById(goods);

        topicDetailVo.setGoods(goodsDtoVo);

        return topicDetailVo;
    }

    @Override
    public TopicRelatedVo topicRelated(Integer id) {

        int limit = Constant.DEFAULT_PAGEHANDLER_LIMIT;
        int page = Constant.DEFAULT_PAGEHANDLER_PAGE;

        PageHelper.startPage(page,limit);
        MarketTopicExample example = new MarketTopicExample();

        int total = topicMapper.selectCountFromTopic();
        List<MarketTopic> marketTopics = topicMapper.selectByExample(example);

        TopicRelatedVo topicRelatedVo = new TopicRelatedVo();
        topicRelatedVo.setList(marketTopics);
        topicRelatedVo.setLimit(limit);
        topicRelatedVo.setPage(page);
        topicRelatedVo.setTotal(total);
        int pages = 0;
        if (total%limit == 0){
            pages = total/limit;
        }else {
            pages = total/limit + 1;
        }
        topicRelatedVo.setPages(pages);
        return topicRelatedVo;
    }

    @Override
    public CommonData<CollectListVo> collectList(BasePageInfo info, Integer type) {
        PageHelper.startPage(info.getPage(),info.getLimit());
        //新建一个相关的example类的对象
        MarketCollectExample example = new MarketCollectExample();
        //设置去重
        example.setDistinct(true);

        List<CollectListVo> collectListVoList = collectMapper.collectListFromGoodsAndCollect(type);
        PageInfo<CollectListVo> pageInfo = new PageInfo<>(collectListVoList);

        return CommonData.data(pageInfo);
    }

    /**
     * @Author xiaowu
     * @Description // 加入或者删除收藏
     * @Date 8:48 2023/1/2
     * @Param [map]  {"type":0,"valueId":1181110}
     * @return {"errno":0,"errmsg":"成功"}
     **/
    @Override
    public void collectAddordelete(Map map,Integer id) {

        int type = (int) map.get("type");
        Byte temp = (byte) type;
        Integer valueId = (Integer) map.get("valueId");
        MarketCollect marketCollect = new MarketCollect();

        marketCollect.setUserId(id);
        marketCollect.setAddTime(new Date());
        marketCollect.setUpdateTime(new Date());
        marketCollect.setType(temp);
        marketCollect.setValueId(valueId);

        //先判断数据库的collect表中有没有该商品，如有则取消，没有则插入
        int count = collectMapper.selectCountByValueId(valueId);
        if (count == 1){
            collectMapper.updateCollectDeleteByValueId(valueId);
        }else {
            collectMapper.insertCollect(marketCollect);
        }
    }

    /**
     * @Author xiaowu
     * @Description //TODO 多个文件上传不需要考虑
     * @Date 14:26 2023/1/2
     * @Param [file]
     * @return int
     **/
    @Override
    public int storageUpload(MultipartFile file) {

        //获取文件名
        String filename = file.getOriginalFilename();
        String suuid = UUID.randomUUID().toString();
        filename = suuid + "-" +filename;

        //获取文件类型
        String contentType = file.getContentType();

        //获取文件大小
        int size = (int) file.getSize();

        UUID uuid = UUID.randomUUID();
        //将UUID和图片文件后缀拼接作为key，作为文件唯一索引
        int index = contentType.indexOf("/");

        String key = uuid.toString() + "." + contentType.substring(index+1);

        //文件实际存放位置
        // 比如我们要保存到D:\tmp路径下，保存的文件名叫banner.png ，我们就要提供一个这样的File
        //设置多级目录，解决所有文件全部都在一个目录内的问题
        int hashCode = filename.hashCode();
        String hexString = Integer.toHexString(hashCode);
        char[] chars = hexString.toCharArray();
        String basePath = "";
        for (char aChar : chars) {
            basePath = basePath + "/" +aChar;
        }
        basePath += "/";

        String path = Constant.BASE_MAPPING_LOCATION + basePath +filename;
        File filetrue = new File(path);
        if (!filetrue.getParentFile().exists()){
            filetrue.getParentFile().mkdirs();
        }

        //这是IO上传存储嘛？
        try {
            file.transferTo(filetrue);
        } catch (IOException e) {
            e.printStackTrace();
        }

        MarketStorage marketStorage = new MarketStorage();
        marketStorage.setKey(key);
        marketStorage.setName(filename);
        marketStorage.setType(contentType);
        marketStorage.setAddTime(new Date());
        marketStorage.setUpdateTime(new Date());
        marketStorage.setSize(size);
        marketStorage.setUrl(Constant.BASE_URL + basePath +filename);

        int affectedrows = storageMapper.insertSelective(marketStorage);
        if(affectedrows == 0){
            return 10000;
        }
        return 200;
    }
}
